package com.gl.order.security.handle;

import cn.hutool.core.util.StrUtil;
import com.gl.order.commom.util.JwtTokenUtils;
import com.gl.order.commom.util.ResponseUtils;
import com.gl.order.commom.ResultBean;
import com.gl.order.config.JwtConfig;
import com.gl.order.security.model.SecurityUser;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @Author: liangSY
 * @Date: 2021/6/8 14:36
 * @ClassName: UnauthorizedEntryPoint
 * 未登录统一处理
 */
@Component
public class UnauthorizedEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        String token = request.getHeader(JwtConfig.tokenHeader);
        if (StrUtil.isBlank(token)) {
            ResponseUtils.responseJson(response, ResultBean.failed(ResultBean.NO_LOGIN, "登录过期，请重新登录！"));
            return;
        }
        token = token.substring(JwtConfig.tokenPrefix.length() + 1);
        SecurityUser securityUser = JwtTokenUtils.getUserInfo(token);
        if (Objects.isNull(securityUser)) {
            String cachUserToken = JwtTokenUtils.timedCache.get(securityUser.getCurrentUserInfo().getId());
            if (!Objects.equals(token, cachUserToken)) {
                ResponseUtils.responseJson(response, ResultBean.failed(ResultBean.NO_LOGIN, "该账号已在其他地方登录！"));
                return;
            }
        }
        ResponseUtils.responseJson(response, ResultBean.failed(ResultBean.NO_LOGIN, "登录过期，请重新登录！"));
    }
}
